import { BrowserWindow, Menu, app, globalShortcut } from "electron"
import { platform } from "os"
import menuconfig from "../config/menu"
import config from "@config"
import setIpc from "./ipcMain"
import cardUtils from '../services/cardUtils'
import { winURL, loadingURL } from "../config/StaticPath"

console.log('-----init windowManager')
var loadWindow = null
var mainWindow = null

function createMainWindow () {
  /**
   * Initial window options
   */
  mainWindow = new BrowserWindow({
    width: 1700,
    minWidth: 1376,
    height: 800,
    useContentSize: true,
    // fullscreen: true, // 全屏
    // frame: false, // 去掉菜单
    show: false,
    frame: config.IsUseSysTitle,
    titleBarStyle: platform().includes("win32") ? "default" : "hidden",
    webPreferences: {
      contextIsolation: false,
      nodeIntegration: true,// 使渲染进程拥有node环境
      webSecurity: false,
      // 如果是开发模式可以使用devTools
      // devTools: process.env.NODE_ENV === "development",
      devTools: true,
      // 在macos中启用橡皮动画
      scrollBounce: process.platform === "darwin",
    },
  })

  setIpc.Mainfunc(mainWindow, config.IsUseSysTitle)

  // 这里设置只有开发环境才注入显示开发者模式
  /* if (process.env.NODE_ENV === "development") {
    menuconfig.push({
      label: "开发者设置",
      submenu: [
        {
          label: "切换到开发者模式",
          accelerator: "CmdOrCtrl+I",
          role: "toggledevtools",
        },
      ],
    })
  } */

  // menuconfig.push({
  //   label: "开发者设置",
  //   submenu: [
  //     {
  //       label: "切换到开发者模式",
  //       accelerator: "CmdOrCtrl+I",
  //       role: "toggledevtools",
  //     },
  //   ],
  // })
  // 载入菜单
  // const menu = Menu.buildFromTemplate([])
  const menu = Menu.buildFromTemplate(menuconfig)
  Menu.setApplicationMenu(menu)
  // Menu.setApplicationMenu(null)
  mainWindow.loadURL(winURL)
  mainWindow.webContents.once("dom-ready", () => {
    if (config.UseStartupChart) loadWindow.destroy()
    mainWindow.show()
  })

  app.on('ready', () => {
    /** 其他代码*/
    globalShortcut.register('F5', () => {
      return false;
    })
  })


  if (process.env.NODE_ENV === "development") {
    mainWindow.webContents.openDevTools(true)
  }

  app.on('will-quit', () => {
    globalShortcut.unregister('F5')
  })

  mainWindow.on("closed", () => {
    mainWindow = null

    app.quit()
  })

  mainWindow.maximize()
}

function loadingWindow () {
  loadWindow = new BrowserWindow({
    width: 800,
    height: 600,
    frame: false,
    backgroundColor: "#222",
    skipTaskbar: true,
    transparent: true,
    resizable: false,
    webPreferences: { experimentalFeatures: true },
  })

  loadWindow.loadURL(loadingURL)

  loadWindow.show()

  setTimeout(() => {
    createMainWindow()
  }, 2000)

  loadWindow.on("closed", () => {
    loadWindow = null
  })
}

function initWindow () {
  if (config.UseStartupChart) {
    return loadingWindow()
  } else {
    return createMainWindow()
  }
}
export default initWindow
